package com.rem.concurrency.multithreading.syn;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;

/**
 * 从银行取现
 * 不加synchronized 锁定账户会存在金额异常
 *
 * @author Rem
 * @date 2021-03-04
 */

public class UnsafeBank {

    public static void main(String[] args) {
        AccountMan account = new AccountMan("共有基金", 100);

        Draw you = new Draw(account, 40, "you");
        Draw wife = new Draw(account, 30, "wife");

        you.start();
        wife.start();

    }

}


@AllArgsConstructor
@NoArgsConstructor
@Data
class AccountMan {
    //账户名称
    private String name;
    //账户余额
    private Integer money;

}

@Data
class Draw extends Thread {

    private AccountMan accountMan;

    private Integer drawIngMoney;

    private Integer nowMoney;

    public Draw(AccountMan accountMan, Integer drawIngMoney, String name) {
        super(name);
        this.accountMan = accountMan;
        this.drawIngMoney = drawIngMoney;
    }

    @SneakyThrows
    @Override
    public void run() {

        //加锁  锁有增删改的对象
        synchronized (accountMan.getMoney()) {
            if (accountMan.getMoney() < drawIngMoney) {
                System.err.println(Thread.currentThread().getName() + "取钱账户余额不足");
                return;
            }
            Thread.sleep(1000);

            //取钱
            accountMan.setMoney(accountMan.getMoney() - drawIngMoney);
            //手里的钱
            System.err.println(Thread.currentThread().getName() + "要取的钱：" + drawIngMoney + ",账户余额：" + accountMan.getMoney());


        }

    }
}